<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>观察者模式</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
</head>

<script>
    // 1、发布者
    class Dep{
        constructor(){
            this.subs = []
        }

        addSub (sub){
            if(sub && sub.update)
                this.subs.push(sub)
        }

        notify (){
            this.subs.forEach(sub => sub.update())
        }
    }
    // 2、订阅者、观察者
    class Watcher{
        constructor(name){
            this.name = name
        }
        update(){
            console.log("update:", this.name)
        }
    }

    // 使用观察者模式
    let watcher1 = new Watcher("观察者1")
    let watcher2 = new Watcher("观察者2")
    let dep = new Dep()

    dep.addSub(watcher1)
    dep.addSub(watcher2)
    dep.notify()

</script>
<body>
    
</body>
</html>